<?php


namespace App\Controller;


use Ucenter\Model\InviteLogModel;
use Ucenter\Model\InviteModel;
use User\Model\UcenterMemberModel;

class AppBaseController extends BaseController
{
    public function _initialize()
    {
        $this->checkSign();
        $this->checkVersion();
//        $this->doDDosDefend();
//        $this->forbiddenFDsoft();
    }

    /**
     * 检查请求
     */
    public function checkSign()
    {
        $req = $_REQUEST;
        if (!$req['imei'] || !$req['nonce'] || !$req['version'] || !$req['sign']) {
            $this->jerror("参数错误，非法操作", 403);
        }
        $sign = $req['sign'];
        unset($req['sign']);
        ksort($req);
        $string_a = http_build_query($req);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $string_sign_temp = $string_a . C("API_KEY");
        //签名步骤三：MD5加密
        $checkSign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $checkSign = strtolower($checkSign);

        if ($sign != $checkSign) {
            $this->jerror("签名错误");
        }
    }

    public function checkVersion()
    {
        $versionBuild = $_REQUEST['version'];
        $device = $_REQUEST['device'];
        $appVersionConfig = C("APP_VERSION");

        if (strtolower($device) == 'ios') {
            $appVersion = $appVersionConfig['ios'];
        } else {
            $appVersion = $appVersionConfig['android'];
        }
        if ((intval($versionBuild) - intval($appVersion['versionBuild']) < 0) && $appVersion['forceUpdate']) {
            $this->jerror("版本过低，请先升级App", 405);
        }
    }



    /**
     * 校验邀请码
     * @param string $code
     * @return bool
     */
    public function checkInviteCode($code = '')
    {
        if ($code == '') {
            return true;
        }
        $InviteModel = new InviteModel();
        $invite = $InviteModel->getByCode($code);

        if ($invite) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 生成邀请信息并增加用户饲料
     * @param int $uid
     * @param string $code
     * @param int $role
     * @return bool
     */
    public function initInviteUser($uid = 0, $code = '', $role = 1)
    {
        if ($code != '') {
            $inviteModel = new InviteModel();
            $inviteLogModel = new InviteLogModel();
            $invite = $inviteModel->getByCode($code);

            if (!$invite) {
                return true;
            }

            $inviteUid = $invite['uid'];

            $data = array(
                'uid' => $uid,
                'invite_uid' => $inviteUid,
                'invite_invite_uid' => 0,
                'create_time' => time(),
                'is_award' => 0
            );
            $ret = M("InviteUser")->add($data);
            unset($data);
            //保存邀请日志
            $data['inviter_id'] = abs($inviteUid);
            $data['uid'] = $uid;
            $data['invite_id'] = $invite['id'];
            $result = $inviteLogModel->addData($data, $role);

            //增加邀请人的邀请码邀请人数
            $invite_info['already_num'] = $invite['already_num'] + 1;
            if ($invite_info['already_num'] == $invite['can_num']) {
                $invite_info['status'] = 0;
            }
            $inviteModel->where(array('id' => $invite['id']))->save($invite_info);
        }
        return true;
    }

    /**
     * 生成邀请码
     * @param $uid
     */
    public function createCode($uid)
    {
        $aTypeId = 1;
        $aCanNum = 1000000;

        $Invite = new InviteModel();
        $data['can_num'] = $aCanNum;
        $data['invite_type'] = $aTypeId;
        $Invite->createUserCode($data, $uid);
    }

    /**
     * 获取uid
     * @return mixed
     */
    public function getUid()
    {
        $token = $this->checkAuthorization();
        return $token['uid'];
    }

    /**商家销售奖励
     * 验证请求token
     * @return bool|mixed|string
     */
    public function checkAuthorization()
    {
        $header = $this->get_all_header();
        if ($header['authorization'] == '[object Undefined]') {
            $this->jerror('请创建钱包', 403);
        }
        //校验登录是否过期
        $authorization = $header['authorization'];
        $token = base64_decode($authorization);
        $token = json_decode($token, true);
        if (!$token['expire_time'] || $token['expire_time'] < time()) {
            $this->jerror('请创建钱包', 403);
        }
        $uid = $token['uid'];
        $user = query_user(['username'], $uid);
        if (!$user || $user['username'] == null) {
            $this->jerror('请创建钱包', 403);
        }
        $status = M("Member")->where(['uid' => $uid])->getField("status");
        if ($status == 0) {
            $this->jerror("您的账户有风险，已被禁用");
        }

        return $token;
    }

    public function get_all_header()
    {
        // 忽略获取的header数据。这个函数后面会用到。主要是起过滤作用
        $ignore = array('host', 'accept', 'content-length', 'content-type');

        $headers = array();
        //这里大家有兴趣的话，可以打印一下。会出来很多的header头信息。咱们想要的部分，都是‘http_'开头的。所以下面会进行过滤输出。
        /*    var_dump($_SERVER);
            exit;*/

        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) === 'HTTP_') {
                //这里取到的都是'http_'开头的数据。
                //前去开头的前5位
                $key = substr($key, 5);
                //把$key中的'_'下划线都替换为空字符串
                $key = str_replace('_', ' ', $key);
                //再把$key中的空字符串替换成‘-’
                $key = str_replace(' ', '-', $key);
                //把$key中的所有字符转换为小写
                $key = strtolower($key);

                //这里主要是过滤上面写的$ignore数组中的数据
                if (!in_array($key, $ignore)) {
                    $headers[$key] = $value;
                }
            }
        }
//输出获取到的header
        return $headers;
    }

    /**
     * 获取用户注册错误信息
     * @param integer $code 错误编码
     * @return string        错误信息
     */
    public function showRegError($code = 0)
    {
        switch ($code) {
            case -1:
                $error = L('') . modC('USERNAME_MIN_LENGTH', 2, 'USERCONFIG') . '-' . modC('USERNAME_MAX_LENGTH', 32, 'USERCONFIG') . L('_ERROR_LENGTH_2_') . L('_EXCLAMATION_');
                break;
            case -2:
                $error = L('_ERROR_USERNAME_FORBIDDEN_') . L('_EXCLAMATION_');
                break;
            case -3:
                $error = L('_ERROR_USERNAME_USED_') . L('_EXCLAMATION_');
                break;
            case -4:
                $error = L('_ERROR_LENGTH_PASSWORD_') . L('_EXCLAMATION_');
                break;
            case -5:
                $error = L('_ERROR_EMAIL_FORMAT_2_') . L('_EXCLAMATION_');
                break;
            case -6:
                $error = L('_ERROR_EMAIL_LENGTH_') . L('_EXCLAMATION_');
                break;
            case -7:
                $error = L('_ERROR_EMAIL_FORBIDDEN_') . L('_EXCLAMATION_');
                break;
            case -8:
                $error = L('_ERROR_EMAIL_USED_2_') . L('_EXCLAMATION_');
                break;
            case -9:
                $error = L('_ERROR_PHONE_FORMAT_2_') . L('_EXCLAMATION_');
                break;
            case -10:
                $error = L('_ERROR_FORBIDDEN_') . L('_EXCLAMATION_');
                break;
            case -11:
                $error = L('_ERROR_PHONE_USED_') . L('_EXCLAMATION_');
                break;
            case -20:
                $error = L('_ERROR_USERNAME_FORM_') . L('_EXCLAMATION_');
                break;
            case -30:
                $error = L('_ERROR_NICKNAME_USED_') . L('_EXCLAMATION_');
                break;
            case -31:
                $error = L('_ERROR_NICKNAME_FORBIDDEN_2_') . L('_EXCLAMATION_');
                break;
            case -32:
                $error = L('_ERROR_NICKNAME_FORM_') . L('_EXCLAMATION_');
                break;
            case -33:
                $error = L('_ERROR_LENGTH_NICKNAME_1_') . modC('NICKNAME_MIN_LENGTH', 2, 'USERCONFIG') . '-' . modC('NICKNAME_MAX_LENGTH', 32, 'USERCONFIG') . L('_ERROR_LENGTH_2_') . L('_EXCLAMATION_');;
                break;
            default:
                $error = L('_ERROR_UNKNOWN_');
        }
        return $error;
    }

    public function checkPassword($uid)
    {
        $password = $_REQUEST['password'];

        if (strlen($password) < 6) {
            $this->jerror("请输入密码");
        }
        $UcenterMemberModel = new UcenterMemberModel();
        $ret = $UcenterMemberModel->verifyUser($uid, $password);
        if (!$ret) {
            $this->jerror("密码错误");
        }
    }


}